package com.example.lotterybackend.dao.handler;

import com.example.lotterybackend.common.utils.EncryptUtil;
import com.example.lotterybackend.dao.dataobject.PhoneNumberEncrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedTypes(PhoneNumberEncrypt.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class UserPhoneTypeHandler extends BaseTypeHandler<PhoneNumberEncrypt> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PhoneNumberEncrypt parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || !StringUtils.hasText(parameter.getValue())) {
            // 设置空值
            ps.setString(i, null);
            return;
        }
        // 进行加密
        String encryptPhoneNumber = EncryptUtil.encryptByAes(parameter.getValue());
        ps.setString(i, encryptPhoneNumber);
    }

    @Override
    public PhoneNumberEncrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String encryptPhoneNumber = rs.getString(columnName);
        if (!StringUtils.hasText(encryptPhoneNumber)) {
            return null;
        }
        String phoneNumber = EncryptUtil.decryptByAes(encryptPhoneNumber);
        return new PhoneNumberEncrypt(phoneNumber);
    }

    @Override
    public PhoneNumberEncrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String encryptPhoneNumber = rs.getString(columnIndex);
        if (!StringUtils.hasText(encryptPhoneNumber)) {
            return null;
        }
        String phoneNumber = EncryptUtil.decryptByAes(encryptPhoneNumber);
        return new PhoneNumberEncrypt(phoneNumber);
    }

    @Override
    public PhoneNumberEncrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String encryptPhoneNumber = cs.getString(columnIndex);
        if (!StringUtils.hasText(encryptPhoneNumber)) {
            return null;
        }
        String phoneNumber = EncryptUtil.decryptByAes(encryptPhoneNumber);
        return new PhoneNumberEncrypt(phoneNumber);
    }
}
